package com.idcheck.rechcustoms;

import android.annotation.SuppressLint;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;

import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Bundle;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import com.idcheck.rechcustoms.ScreenOffAdminReceiver;

import utils.AndroidRootUtils;
import utils.OtherUtil;
import utils.PrefUtils;

import android.content.Context;
import android.os.PowerManager;
import android.os.SystemClock;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class FullscreenActivity extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    private PasswordView passwordView;
    private CountDownTimer mTimer=null; //UI计时
    private EditText companyId;
    private TextView companyName;
    private TextView lanzhengbtn;
    private EditText companyMobile;
    private EditText password;
    private EditText saveMobile;
    private EditText passwordinner;

    private String strPassword="";
    private volatile long resetTimeStamp = 0;
    private volatile long brightTimeStamp = 0;
    private volatile long mCountSetting = 0;
    private volatile long countTimeStamp = 0;
    private int adminId = 0;
    private String adminTel = "";
    private int companySeqId = 0;
//    PowerManager pm;
//    PowerManager.WakeLock wakeLock = null;
    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;


    private boolean mVisible;
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };
    private boolean isLanzheng = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fullscreen);
        mVisible = true;
        if(getSupportActionBar()!=null){

            getSupportActionBar().hide();

        }
        hideBottomUIMenu();
        Log.d("TAG brightness: ",String.valueOf(getScreenBrightness(this.getApplicationContext())));




//        pm = (PowerManager) getApplication().getSystemService(Context.POWER_SERVICE);
//        wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
//                | PowerManager.SCREEN_DIM_WAKE_LOCK, "rech-custom");

        passwordView = (PasswordView) findViewById(R.id.passwordView);
        passwordView.setCipherEnable(false);

        companyMobile = findViewById(R.id.companyPhone);
        password = findViewById(R.id.password);
        passwordinner = findViewById(R.id.password_inner);
        companyId = findViewById(R.id.companyId);
        companyName = findViewById(R.id.companyName);
        saveMobile = findViewById(R.id.savePhone);
        lanzhengbtn = findViewById(R.id.lanzhengbtn);
        //相对字体大小
        SpannableString spRelativeSize = new SpannableString("揽证\n(管理员)");
        RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan((0.5f));
        spRelativeSize.setSpan(relativeSizeSpan, 2, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        lanzhengbtn.setText(spRelativeSize);
        /*companyMobile.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence text, int start, int before, int count) {
//                //text  输入框中改变后的字符串信息
//                //start 输入框中改变后的字符串的起始位置
//                //before 输入框中改变前的字符串的位置 默认为0
//                //count 输入框中改变后的一共输入字符串的数量
//                companyName.setText("输入后字符串 [ " + text.toString() + " ] 起始光标 [ " + start + " ] 输入数量 [ " + count+" ]");

            }

            @Override
            public void beforeTextChanged(CharSequence text, int start, int count,int after) {
//                //text  输入框中改变前的字符串信息
//                //start 输入框中改变前的字符串的起始位置
//                //count 输入框中改变前后的字符串改变数量一般为0
//                //after 输入框中改变后的字符串与起始位置的偏移量
//                System.out.println(text.toString());
//                companyName.setText("输入前字符串 [ " + text.toString() + " ]起始光标 [ " + start + " ]结束偏移量  [" + after + " ]");
            }

            @Override
            public void afterTextChanged(Editable edit) {
                String value = edit.toString();
                resetTimeStamp = System.currentTimeMillis();
                if(value.length() == 11){
                    new FetchCompanyRecvAuthTask(value).execute();
                }
            }
        });*/
//
//
        companyId.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence text, int start, int before, int count) {
//                //text  输入框中改变后的字符串信息
//                //start 输入框中改变后的字符串的起始位置
//                //before 输入框中改变前的字符串的位置 默认为0
//                //count 输入框中改变后的一共输入字符串的数量
//                companyName.setText("输入后字符串 [ " + text.toString() + " ] 起始光标 [ " + start + " ] 输入数量 [ " + count+" ]");

            }

            @Override
            public void beforeTextChanged(CharSequence text, int start, int count,int after) {
//                //text  输入框中改变前的字符串信息
//                //start 输入框中改变前的字符串的起始位置
//                //count 输入框中改变前后的字符串改变数量一般为0
//                //after 输入框中改变后的字符串与起始位置的偏移量
//                System.out.println(text.toString());
//                companyName.setText("输入前字符串 [ " + text.toString() + " ]起始光标 [ " + start + " ]结束偏移量  [" + after + " ]");
            }

            @Override
            public void afterTextChanged(Editable edit) {
                String value = edit.toString();
                resetTimeStamp = System.currentTimeMillis();
                if(value.length() == 9){
                    new FetchCompanyInfoTask(value).execute();
                }
                companyName.setText("");
                findViewById(R.id.sendsubmit).setEnabled(false);
            }
        });



        /*saveMobile.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence text, int start, int before, int count) {
//                //text  输入框中改变后的字符串信息
//                //start 输入框中改变后的字符串的起始位置
//                //before 输入框中改变前的字符串的位置 默认为0
//                //count 输入框中改变后的一共输入字符串的数量
//                companyName.setText("输入后字符串 [ " + text.toString() + " ] 起始光标 [ " + start + " ] 输入数量 [ " + count+" ]");

            }

            @Override
            public void beforeTextChanged(CharSequence text, int start, int count,int after) {
//                //text  输入框中改变前的字符串信息
//                //start 输入框中改变前的字符串的起始位置
//                //count 输入框中改变前后的字符串改变数量一般为0
//                //after 输入框中改变后的字符串与起始位置的偏移量
//                System.out.println(text.toString());
//                companyName.setText("输入前字符串 [ " + text.toString() + " ]起始光标 [ " + start + " ]结束偏移量  [" + after + " ]");
            }

            @Override
            public void afterTextChanged(Editable edit) {
                String value = edit.toString();
                resetTimeStamp = System.currentTimeMillis();
                if(value.length() == 11){
                    new FetchSaveAuthTask(value).execute();
                }
                companyName.setText("");
                findViewById(R.id.sendsubmit).setEnabled(false);
            }
        });*/


        initTimer();

        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        //eventbus
        initView();

        findViewById(R.id.confirm1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phnumber=companyMobile.getText().toString();

                String pass=password.getText().toString();

                if(TextUtils.isEmpty(phnumber)){

                    Toast.makeText(FullscreenActivity.this,"电话号码不能为空",Toast.LENGTH_LONG).show();

                    return ;
                }

                if(11!=phnumber.length()){

                    Toast.makeText(FullscreenActivity.this,"无效的电话号码",Toast.LENGTH_LONG).show();

                    return ;
                }


                if(TextUtils.isEmpty(pass)){
                    Toast.makeText(FullscreenActivity.this,"密码不能为空",Toast.LENGTH_LONG).show();

                    return ;

                }

                resetTimeStamp = System.currentTimeMillis();
                new FetchCompanyRecvAuthTask(phnumber, pass).execute();
            }
        });

        findViewById(R.id.confirm2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phnumber=saveMobile.getText().toString();

                String pass=passwordinner.getText().toString();

                if(TextUtils.isEmpty(phnumber)){

                    Toast.makeText(FullscreenActivity.this,"电话号码不能为空",Toast.LENGTH_LONG).show();

                    return ;
                }

                if(11!=phnumber.length()){

                    Toast.makeText(FullscreenActivity.this,"无效的电话号码",Toast.LENGTH_LONG).show();

                    return ;
                }


                if(TextUtils.isEmpty(pass)){
                    Toast.makeText(FullscreenActivity.this,"密码不能为空",Toast.LENGTH_LONG).show();

                    return ;

                }

                resetTimeStamp = System.currentTimeMillis();
                new FetchSaveAuthTask(phnumber, pass).execute();
                companyName.setText("");
                findViewById(R.id.sendsubmit).setEnabled(false);
            }
        });

        findViewById(R.id.selfbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent = new Intent(FullscreenActivity.this, ChooseActivity.class);
                startActivity(intent);
                resetTimeStamp = System.currentTimeMillis();

            }
        });

        findViewById(R.id.recvbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
                resetTimeStamp = System.currentTimeMillis();

            }
        });

        findViewById(R.id.sendbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
                findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
                findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                resetTimeStamp = System.currentTimeMillis();

                companyMobile.setEnabled(true);
                companyMobile.requestFocus();
                companyMobile.setSelection(0);
            }
        });

        findViewById(R.id.lanzhengbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
                findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
                findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                resetTimeStamp = System.currentTimeMillis();

                companyMobile.setEnabled(true);
                companyMobile.requestFocus();
                companyMobile.setSelection(0);

                isLanzheng = true;
            }
        });

        findViewById(R.id.sendback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetView();
            }
        });
        findViewById(R.id.sendback1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetView();
            }
        });
        findViewById(R.id.saveback1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetView();
            }
        });
        findViewById(R.id.saveback2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetView();
            }
        });
        findViewById(R.id.savesubmit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText savePhone = findViewById(R.id.savePhone);
                new FetchSaveOpenTask(savePhone.getText().toString()).execute();
            }
        });
        findViewById(R.id.ordersubmit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(FullscreenActivity.this, AppointmentListActivity.class));
            }
        });

        findViewById(R.id.sendsubmit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = adminTel;

                new FetchSendOpenTask(companySeqId,phone,adminId).execute();
            }
        });
        findViewById(R.id.mainbtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetView();

            }
        });
        findViewById(R.id.textDate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCountSetting ++;
                countTimeStamp = System.currentTimeMillis();

                if(mCountSetting > 4){
                    findViewById(R.id.view4).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
                    findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                    findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                    findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                    findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                    saveMobile.setEnabled(true);
                    saveMobile.setText("");
                    resetTimeStamp = System.currentTimeMillis();
                    mCountSetting = 0;
                }
            }
        });
        findViewById(R.id.button0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("0");
                SendPassword();
            }
        });

        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("1");
                SendPassword();
            }
        });
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("2");
                SendPassword();
            }
        });
        findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("3");
                SendPassword();
            }
        });
        findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("4");
                SendPassword();
            }
        });
        findViewById(R.id.button5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("5");
                SendPassword();
            }
        });
        findViewById(R.id.button6).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("6");
                SendPassword();
            }
        });
        findViewById(R.id.button7).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("7");
                SendPassword();
            }
        });
        findViewById(R.id.button8).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("8");
                SendPassword();
            }
        });
        findViewById(R.id.button9).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.add("9");
                SendPassword();
            }
        });
        findViewById(R.id.button11).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordView.delete();
            }
        });

        findViewById(R.id.main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Date date = new Date(System.currentTimeMillis());
                int hours = date.getHours();
                int minutes = date.getMinutes();
                int seconds = date.getSeconds();
                if(hours > 21 || hours < 7){
                    brightTimeStamp =  System.currentTimeMillis();
                    setAppScreenBrightness(200);
                }


            }
        });
        setAppScreenBrightness(200);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay

    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mVisible = true;


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unInitTimer();
    }
    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
    }




    private void SendPassword(){
        if(passwordView.getPassword().length() == 6){
            new FetchRecvOpenTask(passwordView.getPassword()).execute();
        }
    }
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }
    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (9999999 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!FullscreenActivity.this.isFinishing()) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 \n HH:mm:ss");// HH:mm:ss
//获取当前时间
                        Date date = new Date(System.currentTimeMillis());
                        TextView datetext = (TextView)findViewById(R.id.textDate);
                        datetext.setText(simpleDateFormat.format(date));
                        TextView weektext = (TextView)findViewById(R.id.textWeek);
                        weektext.setText(getWeek());
                        if(resetTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - resetTimeStamp;
                            if(timeOut > 180000){
                                resetView();
                            }
                        }
                        if(brightTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - brightTimeStamp;
                            if(timeOut > 3600000){
                                int hours = date.getHours();
                                int minutes = date.getMinutes();
                                int seconds = date.getSeconds();
                                if(hours > 19 || hours < 7){
                                    brightTimeStamp =  System.currentTimeMillis();
                                    setAppScreenBrightness(100);
                                }
                                brightTimeStamp = 0;
                            }
                        }

                        if(countTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - countTimeStamp;
                            if(timeOut > 3000){
                                mCountSetting = 0;
                                countTimeStamp = 0;
                            }
                        }

                        int hours = date.getHours();
                        int minutes = date.getMinutes();
                        int seconds = date.getSeconds();
                        if(hours == 6 && minutes == 0 && seconds < 10){
                            setAppScreenBrightness(200);
                        }
                        if(hours == 22 && minutes == 0 && seconds < 10){
                            setAppScreenBrightness(100);
                        }

                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public static String getWeek(){
        Calendar cal = Calendar.getInstance();
        int i = cal.get(Calendar.DAY_OF_WEEK);
        switch (i) {
            case 1:
                return "星期日";
            case 2:
                return "星期一";
            case 3:
                return "星期二";
            case 4:
                return "星期三";
            case 5:
                return "星期四";
            case 6:
                return "星期五";
            case 7:
                return "星期六";
            default:
                return "";
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message) {
        switch (message.what) {
            case 1000://postinfoForWechatQR 获取二维码信息

                EventMessageForOpenGrid(message.obj);
                break;
            case 1200:
                restartApplication();
                break;
            case 1300:
                EventMessageForAuth(message.obj);
                break;
            case 1400:
                EventMessageForCompany(message.obj);
                break;
            case 1500:
                EventMessageForSend(message.obj);
                break;
            case 1600:
                EventMessageForSaveAuth(message.obj);
                break;
            case 1700:
                EventMessageForSaveOpen(message.obj);
                break;
            case 2100:
                EventMessageForXianchangCun();
                break;
            case 2200:
                resetView();
                break;
            case 10000:
                EventMessageForWait();
                break;
            default:
                EventMessageForError(message.what);
                break;

        }
    }

    private void EventMessageForXianchangCun() {
        findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
        findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
        companyId.setEnabled(true);
        companyId.setText("");
        companyId.requestFocus();
        adminId = Integer.parseInt(PrefUtils.getString(FullscreenActivity.this, "adminid", "0"));
        resetTimeStamp = System.currentTimeMillis();
    }

    private void EventMessageForWait(){
        Toast.makeText(FullscreenActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
    }
    private void EventMessageForError(int what){
        switch(what){
            case 1101:
                Toast.makeText(FullscreenActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                break;
            case 1301:
                if(OtherUtil.isKeyboardActive(getWindow())){
                    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
                }
                resetView();
                break;
            case 1401:
                if(OtherUtil.isKeyboardActive(getWindow())){
                    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
                }
                resetView();
                break;
            case 1501:
                Toast.makeText(FullscreenActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;
            case 1701:
                Toast.makeText(FullscreenActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                break;

        }
    }
    private void initView(){
        findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
        findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
        findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
        findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
        findViewById(R.id.view4).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
        findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
        findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
        findViewById(R.id.step11).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
        findViewById(R.id.step12).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
        companyMobile.setEnabled(false);
        companyId.setEnabled(false);
        saveMobile.setEnabled(false);
        companyMobile.setText("");
        saveMobile.setText("");
        companyName.setText("");
        companyId.setText("");
        findViewById(R.id.sendsubmit).setEnabled(false);
        passwordView.clear();
        this.resetTimeStamp = 0;
        this.brightTimeStamp = 0;
        this.mCountSetting = 0;
        this.countTimeStamp = 0;
        this.adminId = 0;
        this.adminTel = "";
        this.companySeqId = 0;

        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    }
    private void resetView(){

        findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
        findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
        findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
        findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
        findViewById(R.id.view4).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
        findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
        findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
        findViewById(R.id.step11).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
        findViewById(R.id.step12).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
        companyMobile.setEnabled(false);
        companyId.setEnabled(false);
        saveMobile.setEnabled(false);
        companyMobile.setText("");
        saveMobile.setText("");
        password.setText("");
        passwordinner.setText("");
        companyName.setText("");
        companyId.setText("");
        findViewById(R.id.sendsubmit).setEnabled(false);
        passwordView.clear();
        this.resetTimeStamp = 0;
        this.brightTimeStamp = 0;
        this.mCountSetting = 0;
        this.countTimeStamp = 0;
        this.adminId = 0;
        this.adminTel = "";
        this.companySeqId = 0;

        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
//        restartApplication();
    }
    private void resetViewMessage(){
        Message message = new Message();
        message.what=1200;
        EventBus.getDefault().post(message);
    }
    private void EventMessageForSaveOpen(Object obj){
        try{
            findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view4).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){

                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.right);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }else{
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.error);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }

        }catch(Exception e){
            ImageView resultimg = findViewById(R.id.resultimg);
            resultimg.setImageResource(R.drawable.warning);
            TextView resulttext = findViewById(R.id.resulttext);
            resulttext.setText("请检查网络");
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    t.cancel();
                    resetViewMessage();
                }
            }, 5000);
        }
    }
    private void EventMessageForSaveAuth(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                PrefUtils.setString(this, "adminid", result.getJSONObject("data").getString("id"));
                findViewById(R.id.step11).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                findViewById(R.id.step12).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
//                companyId.setEnabled(true);
//                companyId.setText("");
//                companyId.requestFocus();
                int count = result.getJSONObject("data").getInt("count");
                if(count != 0){
                    TextView saveresult = findViewById(R.id.saveresult);
                    String text = "有"+String.valueOf(count)+"空位";
                    saveresult.setText(text);
                    saveresult.setTextColor(Color.BLACK);
                    findViewById(R.id.savesubmit).setEnabled(true);
                    findViewById(R.id.ordersubmit).setEnabled(true);
                }else{
                    TextView saveresult = findViewById(R.id.saveresult);
                    String text = "暂无空位";
                    saveresult.setText(text);
                    saveresult.setTextColor(Color.RED);
                    findViewById(R.id.savesubmit).setEnabled(false);
                    findViewById(R.id.ordersubmit).setEnabled(false);
                }
                resetTimeStamp = System.currentTimeMillis();
            }else{
                findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.warning);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }

        }catch(Exception e){
            findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            ImageView resultimg = findViewById(R.id.resultimg);
            resultimg.setImageResource(R.drawable.warning);
            TextView resulttext = findViewById(R.id.resulttext);
            resulttext.setText("网络错误");
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    t.cancel();
                    resetViewMessage();
                }
            }, 5000);
        }
    }
    private void EventMessageForSend(Object obj){
        try{
            findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view3).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.right);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);

            }else{

                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.warning);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);

            }

        }catch(Exception e){
            ImageView resultimg = findViewById(R.id.resultimg);
            resultimg.setImageResource(R.drawable.warning);
            TextView resulttext = findViewById(R.id.resulttext);
            resulttext.setText("网络错误");
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    t.cancel();
                    resetViewMessage();
                }
            }, 5000);
        }
    }
    private void EventMessageForCompany(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                findViewById(R.id.step1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
                findViewById(R.id.step2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
//                companyId.setEnabled(true);
//                companyId.setText("");
//                companyId.requestFocus();
                String val = result.getJSONObject("data").getString("companyname");
                adminTel = result.getJSONObject("data").getString("contact");
                companySeqId = result.getJSONObject("data").getInt("companyid");
                companyName.setText(val);
                companyName.setTextColor(Color.BLACK);
                findViewById(R.id.sendsubmit).setEnabled(true);
                resetTimeStamp = System.currentTimeMillis();
            }else{
                //Toast.makeText(FullscreenActivity.this,result.getJSONObject("data").getString("msg"),Toast.LENGTH_LONG);
                companyName.setText(result.getString("msg"));
                companyName.setTextColor(Color.RED);
                //resetView();
            }

        }catch(Exception e){
            resetView();
        }
    }
    private void EventMessageForAuth(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                PrefUtils.setString(this, "adminid", result.getJSONObject("data").getString("id"));
                if (isLanzheng){
                    startActivity(new Intent(FullscreenActivity.this, GridListActivity.class));
                    isLanzheng = false;
                } else {
                    startActivity(new Intent(FullscreenActivity.this, ChooseCunZhengTypeActivity.class));
                }

            }else{
                View cv = getWindow().getDecorView();
                AlertDialog.Builder adbuilder = new AlertDialog.Builder(cv.getContext());
                adbuilder.setTitle(result.getString("msg"));
                adbuilder.setMessage("2秒后自动关闭！");
                adbuilder.setCancelable(true);
                final AlertDialog dlg = adbuilder.create();
                dlg.show();
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        dlg.dismiss();
                        t.cancel();
                    }
                }, 5000);
                //Toast.makeText(FullscreenActivity.this,result.getString("msg"),Toast.LENGTH_LONG);
            }

        }catch(Exception e){
            resetView();
        }
    }
    private void EventMessageForOpenGrid(Object obj){

        try{
            findViewById(R.id.view1).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view2).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,1));
            findViewById(R.id.view0).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT,0));
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){

                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.right);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }else{
                ImageView resultimg = findViewById(R.id.resultimg);
                resultimg.setImageResource(R.drawable.error);
                TextView resulttext = findViewById(R.id.resulttext);
                resulttext.setText(result.getString("msg"));
                final Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        t.cancel();
                        resetViewMessage();
                    }
                }, 5000);
            }

        }catch(Exception e){
            ImageView resultimg = findViewById(R.id.resultimg);
            resultimg.setImageResource(R.drawable.warning);
            TextView resulttext = findViewById(R.id.resulttext);
            resulttext.setText("请检查网络");
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    t.cancel();
                    resetViewMessage();
                }
            }, 5000);
        }

    }
    private int getScreenBrightness(Context context) {
        ContentResolver contentResolver = context.getContentResolver();
        int defVal = 125;
        return Settings.System.getInt(contentResolver,
                Settings.System.SCREEN_BRIGHTNESS, defVal);
    }
    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
    private void setAppScreenBrightness(int birghtessValue) {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = birghtessValue / 255.0f;
        window.setAttributes(lp);
    }

}

